package cn.caskm.souvenirshopsystem.service.impl;

import cn.caskm.souvenirshopsystem.constants.BizConstants;
import cn.caskm.souvenirshopsystem.domain.Result;
import cn.caskm.souvenirshopsystem.domain.dto.PageDTO;
import cn.caskm.souvenirshopsystem.domain.po.MessageWall;
import cn.caskm.souvenirshopsystem.domain.po.StudentUser;
import cn.caskm.souvenirshopsystem.domain.query.MessageWallQuery;
import cn.caskm.souvenirshopsystem.domain.vo.MessageWallVO;
import cn.caskm.souvenirshopsystem.exceptions.BizException;
import cn.caskm.souvenirshopsystem.mapper.MessageWallMapper;
import cn.caskm.souvenirshopsystem.service.MessageWallService;
import cn.caskm.souvenirshopsystem.service.StudentUserService;
import cn.caskm.souvenirshopsystem.utils.UserContext;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class MessageWallServiceImpl extends ServiceImpl<MessageWallMapper, MessageWall> implements MessageWallService {

    private final StudentUserService studentUserService;

    @Override
    public Result<PageDTO<MessageWallVO>> page(MessageWallQuery query) {
        // 获取参数
        Long pageNum = query.getPageNum();
        if (pageNum == null) {
            pageNum = BizConstants.DEFAULT_PAGE_NUM;
        }
        Long pageSize = query.getPageSize();
        if (pageSize == null) {
            pageSize = BizConstants.DEFAULT_PAGE_SIZE;
        }

        // 查询数据
        Page<MessageWall> page = lambdaQuery()
                .eq(query.getUserId() != null, MessageWall::getUserId, query.getUserId())
                .eq(StrUtil.isNotBlank(query.getMessageType()), MessageWall::getMessageType, query.getMessageType())
                .eq(StrUtil.isNotBlank(query.getStatus()), MessageWall::getStatus, query.getStatus())
                .orderByDesc(MessageWall::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        List<MessageWall> messages = page.getRecords();
        if (CollUtil.isEmpty(messages)) {
            return Result.success(PageDTO.empty());
        }

        // 获取用户信息
        Set<Integer> userIds = messages.stream().map(MessageWall::getUserId).collect(Collectors.toSet());
        Map<Integer, StudentUser> userMap = Collections.emptyMap();
        if (CollUtil.isNotEmpty(userIds)) {
            List<StudentUser> users = studentUserService.lambdaQuery()
                    .in(StudentUser::getId, userIds)
                    .list();
            if (CollUtil.isNotEmpty(users)) {
                userMap = users.stream().collect(Collectors.toMap(StudentUser::getId, u -> u));
            }
        }

        // 组装VO
        List<MessageWallVO> result = new ArrayList<>(messages.size());
        for (MessageWall message : messages) {
            MessageWallVO vo = BeanUtil.copyProperties(message, MessageWallVO.class);
            StudentUser user = userMap.get(message.getUserId());
            if (user != null) {
                vo.setUserName(user.getName());
                vo.setUserAvatar(user.getAvatar());
            }
            result.add(vo);
        }

        return Result.success(PageDTO.of(result, page.getPages(), page.getTotal()));
    }

    @Override
    public Result<MessageWallVO> getDetail(Integer messageId) {
        MessageWall message = getById(messageId);
        if (message == null) {
            throw new BizException("留言不存在");
        }

        MessageWallVO vo = BeanUtil.copyProperties(message, MessageWallVO.class);
        
        // 获取用户信息
        StudentUser user = studentUserService.getById(message.getUserId());
        if (user != null) {
            vo.setUserName(user.getName());
            vo.setUserAvatar(user.getAvatar());
        }

        return Result.success(vo);
    }

    @Override
    public Result<Void> publishMessage(MessageWall messageWall) {
        // 设置发布信息
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new BizException("用户未登录");
        }

        messageWall.setUserId(userId.intValue());
        messageWall.setCreateTime(LocalDateTime.now());
        messageWall.setUpdateTime(LocalDateTime.now());
        messageWall.setStatus("0"); // 默认正常状态

        // 根据内容判断留言类型
        if (StrUtil.isNotBlank(messageWall.getContent()) && StrUtil.isNotBlank(messageWall.getImage())) {
            messageWall.setMessageType("2"); // 文字+图片
        } else if (StrUtil.isNotBlank(messageWall.getImage())) {
            messageWall.setMessageType("1"); // 图片
        } else {
            messageWall.setMessageType("0"); // 文字
        }

        save(messageWall);
        return Result.success();
    }

    @Override
    public Result<Void> deleteMessage(Integer messageId) {
        Long userId = UserContext.getUser();
        if (userId == null) {
            throw new BizException("用户未登录");
        }

        MessageWall message = getById(messageId);
        if (message == null) {
            throw new BizException("留言不存在");
        }

        // 只能删除自己的留言
        if (!message.getUserId().equals(userId.intValue())) {
            throw new BizException("无权删除他人留言");
        }

        removeById(messageId);
        return Result.success();
    }

    @Override
    public Result<Void> updateStatus(Integer messageId, String status) {
        MessageWall message = getById(messageId);
        if (message == null) {
            throw new BizException("留言不存在");
        }

        message.setStatus(status);
        message.setUpdateTime(LocalDateTime.now());
        updateById(message);
        return Result.success();
    }
}
